/*
 * @lc app=leetcode.cn id=543 lang=golang
 *
 * [543] 二叉树的直径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func diameterOfBinaryTree(root *TreeNode) int {
	var diameter func(node *TreeNode) int
	ans := 0
	diameter = func(node *TreeNode) int {
		if node == nil {
			return 0
		}
		l := diameter(node.Left)
		r := diameter(node.Right)

		if l+r > ans {
			ans = l + r
		}
		if l > r {
			return l + 1
		}
		return r + 1

	}
	diameter(root)
	return ans
}

// @lc code=end

